﻿using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Collections.Generic;

namespace 税控接口.Common
{
    class handleHttp
    {
     

        #region 通用Get方法，可以处理http与https，返回数据，返回String
        /// <summary>
        /// 通用Get方法，可以处理http与https，返回数据，返回String
        /// </summary>
        /// <param name="url">请求的url地址</param>
        /// <returns>http GET成功后返回的数据，失败抛WebException异常</returns>
        public static string Get(string url)
        {
            System.GC.Collect();
            string result = "";

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            //请求url以获取数据
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "GET";

                //设置代理
                //WebProxy proxy = new WebProxy();
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);
                //request.Proxy = proxy;

                //获取服务器返回
                response = (HttpWebResponse)request.GetResponse();

                //获取HTTP返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            #region 忽略错误，外层统一处理
            //catch (System.Threading.ThreadAbortException e)
            //{
            //    // Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
            //    System.Threading.Thread.ResetAbort();
            //    throw new Exception(e.ToString());
            //}
            //catch (WebException e)
            //{
            //    // Log.Error("HttpService", e.ToString());
            //    if (e.Status == WebExceptionStatus.ProtocolError)
            //    {
            //        //Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
            //        //  Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
            //    }
            //    throw new Exception(e.ToString());
            //}
            //catch (Exception e)
            //{
            //    //  Log.Error("HttpService", e.ToString());
            //    throw new Exception( "Common.HandleHttp" e.Message);
            //}
            #endregion
            finally
            {
                #region  关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
                #endregion
            }
            return result;
        }
        #endregion

        #region https Get方式访问必须返回证书认证正确
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开
            return true;
        }
        #endregion


        #region 通用Post方法,http与https一致字符串
        /// <summary>
        /// 通用Post方法,http与https一致字符串
        /// </summary>
        /// <param name="obj">发送的对象</param>
        /// <param name="url">发送的目标网址</param>
        /// <returns>发送后的返回值</returns>
        public static string Post<T>(T obj, string url)
        {
            var s = Common.handleJSON.Serialize(obj);
            return Post(s, url);
        }
        #endregion

        #region 通用Post方法,http与https一致字符串
        /// <summary>
        /// 通用Post方法,http与https一致字符串
        /// </summary>
        /// <param name="str">发送的字符串</param>
        /// <param name="url">发送的目标网址</param>
        /// <returns>发送后的返回值</returns>
        public static string Post(string str, string url)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(str);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.Timeout = 10000000;
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            finally
            {
                #region  关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
                #endregion
            }
        }
        #endregion

    }
}
